﻿@using SmartCode
@using SmartCode.Db
@model BuildContext
@{
    var project = Model.Project;
    var dbSource = Model.GetDataSource<DbSource>();
    var table = Model.GetCurrentTable();
    var pkCol = table.PKColumn;
    if (pkCol == null)
    {
        throw new SmartCodeException($"{table.Name} can not find PKColumn！");
    }
    var autoIncrement = table.AutoIncrement;
    var prefix = dbSource.DbProvider.ParameterPrefix;
}

<!--新增-->
<Statement Id="Insert">
    INSERT INTO @table.Name
    (
    @for (var colIndex = 0; colIndex < table.Columns.Count(); colIndex++)
    {
        var col = table.Columns.ElementAt(colIndex);
        @if (!col.AutoIncrement)
        {
            @Html.PadLeft(6)@col.Name@(colIndex == table.Columns.Count() - 1 ? "" : ",")
            @Html.NewLine()
        }
    }
    )
    VALUES
    (
    @for (var colIndex = 0; colIndex < table.Columns.Count(); colIndex++)
    {
        var col = table.Columns.ElementAt(colIndex);
        @if (!col.AutoIncrement)
        {
            @Html.PadLeft(6)@prefix@col.ConvertedName@(colIndex == table.Columns.Count() - 1 ? "" : ",")
            @Html.NewLine()
        }
    }
    )
    @if (autoIncrement)
    {
        @switch (dbSource.DbRepository.DbProvider)
        {
            case DbProvider.MariaDB:
            case DbProvider.MySql:
                {
                    <text>;Select Last_Insert_Id();</text>
                    break;
                }
            case DbProvider.SqlServer:
                {
                    <text>;Select Scope_Identity();</text>
                    break;
                }
            case DbProvider.PostgreSql:
                {
                    <text>Returning @pkCol.Name;</text>
                    break;
                }
        }
        @Html.NewLine()
    }
</Statement>